<?php
/**
 * @file $HeadURL: imagelibrary.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-12-22 下午12:51:56 $
 * @brief 
 */
namespace haibao\www\business;

use haibao\www\Config;

class ImageLibrary extends \haibao\www\business\Base{
	
	/**
	 * @param int/array $id
	 */
	public static function getImagesById($imageIds){
		if(!$imageIds){
			throw new BusinessException('图片ID传递错误');
		}
		$data = new \haibao\cms\data\ImageLibrary();
		return $data->getImageById((array)$imageIds);
	}
	/**
	 * 通过图片id得图片地址
	 * @param array/int $imageId
	 * @return array($imageId=>$url)
	 */
	public static function getImageUrlById($imageIds){
		$data = new \haibao\cms\data\ImageLibrary();
		return $data->getImageUrlById($imageIds);
	}
	/**
	 * 批量下载图片
	 * @param int/array $imageIds
	 * @throws BusinessException
	 */
	public static function downloadImage($imageIds){
		self::checkOperation(self::FUNC_CODE_IMAGE_LIBRARY_DOWNLOAD);
		
		$models = self::getImagesById((array)$imageIds);
		if(!$models){
			throw new BusinessException('下载失败');
		}
		$saveFilename = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_UPLOAD_BASE_PATH);
		if(file_exists($saveFilename)){
			chmod($saveFilename, 0777);
			unlink($saveFilename);
		}
		$zip = new \ZipArchive();
		$res = $zip->open($saveFilename, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE);
		
		if ( $res === TRUE) {
			foreach ($models as $model){
				self::checkImage($model->Id, $model->Filename);
				$filePath = self::getSaveImagePath($model->Filename);
				$zip->addFile($filePath , basename($filePath));
			}
			$zip->close();
			self::saveOperateHistory(self::FUNC_CODE_IMAGE_LIBRARY_DOWNLOAD, $models);
			return $saveFilename;
		}
	}
	
	/**
	 * 筛选图片
	 */
	public static function getImageLibraryByQuery($query){
		self::checkOperation(self::FUNC_CODE_IMAGE_LIBRARY_MANAGE);
		
		if(!$query){
			$query = new \haibao\cms\model\filter\ImageLibrary();
		}
		$data = new \haibao\cms\data\ImageLibrary();
		$imageList = $data->getImageLibraryByQuery($query);
		self::dataConvert($imageList);
		
		return $imageList;
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	public static function saveUpload($file,$upSource = \haibao\www\model\data\ImageLibrary::UPLOAD_SOURCE_QUESTION){		
		$storagePath = self::getUploadStoragePath($file['name']);
		$data = new \haibao\www\data\ImageLibrary();
		
		$userId = \haibao\www\model\data\ImageLibrary::QUESTION_DEFAULT_USER_ID;
		$userName = \haibao\www\model\data\ImageLibrary::QUESTION_DEFAULT_USER_NAME;
		$picId = $data->saveImage($file['tmp_name'], $storagePath, $userId,$userName,$upSource);
		if(empty($picId)){
			throw new BusinessException('类型'.$upSource.'的图片上传失败');
		}
        $savePath = self::generateImage($storagePath, file_get_contents($file['tmp_name']));
		return array(
			'id' => $picId,
			'imageUrl' => $storagePath,
			'savePath' => $savePath,
		);
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	public static function saveImageLibrary($model){
		self::checkOperation(self::FUNC_CODE_IMAGE_LIBRARY_EDIT);
		
		if(!$model->Id){
			throw new BusinessException('图片ID传递错误');
		}
		if(!$model->CategoryId){
			throw new BusinessException('图片分类不能为空');
		}
		if(!$model->Source){
			throw new BusinessException('图片来源不能为空');
		}
		$model->Id = explode(',', $model->Id);
		if($model->Description && $model->Tags){
			$model->Editor = self::getCurrentUser()->Id;
		}else{

			$model->Editor = 0;
		}
		$model->UserName = self::getCurrentUser()->UserName;
		$data = new \haibao\cms\data\ImageLibrary();
		$data->updateImageLibrary($model);
		
		self::saveOperateHistory(self::FUNC_CODE_IMAGE_LIBRARY_UPLOAD, $model->toArray(true,true));
	}
	
	/**
	 * @param \haibao\cms\model\data\ImageLibrary $model
	 */
	public static function updateImageStatus($id, $status = \haibao\cms\model\data\ImageLibrary::STATUS_ENABLE){
		if(!isset($id)){
			throw new BusinessException('图片ID不能为空');
		}
		
		$data = new \haibao\cms\data\ImageLibrary();
		$data->updateImageStatus($id, $status, self::getCurrentUser()->UserName);
		
		self::saveOperateHistory(self::FUNC_CODE_IMAGE_LIBRARY_DELETE, array($id, $status));
	}
	
	public static function deleteImage($id){
		self::updateImageStatus($id, \haibao\cms\model\data\ImageLibrary::STATUS_DELETE, self::getCurrentUser()->UserName);
	}
	
	/**
	 * 彻底删除图片，包括数据库、文件存储、MongoDB中的全部内容
	 */
	public static function realDeleteImage(){
// 		$data = new \haibao\cms\data\ImageLibrary();
	}
	
	/**
	 * 得图片内容
	 * @param unknown_type $picId
	 * @return Ambigous <NULL, multitype:>
	 */
	public function getImgageById($picId){
		$data = new \haibao\cms\data\ImageLibrary();
		return $data->getImgageByMongo($picId);
	}
	
	/**
	 * 获取要上传文件的存储路径
	 * @return string /upload/question/2014/1230/1419842617.9557.jpg
	 */
	public static function getUploadStoragePath($orgionName){
		$basePath = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_UPLOAD_BASE_PATH).date('Y').DIRECTORY_SEPARATOR.date('md').DIRECTORY_SEPARATOR.microtime(true);
		$extension = pathinfo($orgionName);
		$basePath .= '.' . strtolower($extension['extension']);
		return str_replace(array('/', '\\'), '/', $basePath);
	}
	
	/**
	 * 保存图片到存储
	 * @param int $id
	 * @param string $imageUrl
	 */
	private static function saveImage2Storage($id, $imageUrl){
		$data = new \haibao\cms\data\ImageLibraryMongo();
		$collection = $data->getFileById($id, $imageUrl);
		$imageContent = $collection->getBytes();
		$fileArr = (array)$collection;
		self::generateImage($fileArr['file']['Filename'], $imageContent);
	}
	
	/**
	 * 保存生图片
	 */
	private static function generateImage($path, $stream){
		$savePath = self::getSaveImagePath($path);
		self::createDir($savePath);
		file_put_contents($savePath, $stream);

        return $savePath;
	}
	
	/**
	 * 获取文件保存路径
	 */
	private static function getSaveImagePath($path){
// 		return \haibao\frame\Environment::path() . '/web' . $path;
		return \haibao\frame\Environment::path() . $path;
	}
	
	/**
	 * 创建文件保存路径
	 */
	private static function createDir($path){
		$path = pathinfo( $path );
		return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
	}
	

	
	private static function dataConvert(&$imageList){
		foreach ($imageList as $key=>$list){
			$fileNameKey = \haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_FILENAME;
			$picIdKey = \haibao\cms\model\filter\ImageLibrary::CONDITION_FIELD_NAME_PICID;
			//self::checkImage($list->$picIdKey, $list->$fileNameKey);
			$list->$fileNameKey = ltrim($list->$fileNameKey,'/');
			$list->$fileNameKey = \haibao\frame\Environment::getConfig('APP_DOMAIN').$list->$fileNameKey;
			//$list->$fileNameKey = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::IMAGE_UPLOAD_BASE_PATH).$list->$fileNameKey;
		}
	}
	
	/**
	 * 检查图片是否存在，没有从MongoDB中取出后生成图片
	 */
	private static function checkImage($id, $imageUrl){
		if(!$id){
			return false;
		}
		$path = self::getSaveImagePath($imageUrl);
		
		$fullUrl = \haibao\frame\http\HttpEnvironment::domain().$imageUrl;
// 		$urlStr = substr(file_get_contents($fullUrl), 0, 10);	// 取图片中的一段信息来检查图片是否存在
// 		if(!file_exists($path) && empty($urlStr)){
		if(!file_exists($path)){
			$data = new \haibao\cms\data\ImageLibraryMongo();
			$collection = $data->getFileById($id, $imageUrl);
			if($collection){
				$stream = $collection->getBytes();
				self::generateImage($imageUrl, $stream);
			}
		}
	}
	/**
	 * 图片统计
	 */
	public static function getImageStatisticList($queryArr){
		$data = new \haibao\cms\data\ImageLibrary();
		return $data->getImageStatisticList($queryArr);
	}
}

